﻿using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
using System.Linq;

namespace ELab.Serialization.Data
{
    public class SurveyProvider
    {
        private string _fileName = ELab.Settings.ELabSettings.AssemblyDirectory + "\\surveys.lab";
        private List<Survey> surveys = null;
        public List<Survey> Surveys
        {
            get
            {
                if (surveys != null) return surveys;
                XmlSerializer x = new XmlSerializer(typeof(List<Survey>));
                using (Stream stream = new FileStream(_fileName, FileMode.OpenOrCreate, FileAccess.Read, FileShare.None))
                {
                    if (stream.Length > 0)
                    {
                        var obj = x.Deserialize(stream);
                        if (obj != null)
                        {
                            surveys = (List<Survey>)obj;
                        }
                    }
                }
                if (surveys == null) return new List<Survey>();
                return surveys;
            }
        }

        public void Add(params Survey[] dest)
        {
            var sv = this.Surveys;
            var max = (sv == null || sv.Count == 0 ? 0 : sv.Max(x => x.ID));
            foreach (var survey in dest)
            {
                survey.ID = max + 1;
                surveys = this.Surveys.AddExt(survey);
                max++;
            }
        }

        public void Save()
        {
            if (this.Surveys == null) return;
            if (File.Exists(_fileName)) File.Delete(_fileName);

            XmlSerializer x = new XmlSerializer(typeof(List<Survey>));
            using (Stream stream = new FileStream(_fileName, FileMode.OpenOrCreate, FileAccess.ReadWrite))
                x.Serialize(stream, this.Surveys);
            surveys = null;

        }

        public void Remove(Survey survey)
        {
            var surveyCheck = this.Surveys.FirstOrDefault(x => x.ID == survey.ID);
            this.Surveys.Remove(surveyCheck);
        }
    }
}
